package com.qiyu.bigdata.reportexcel;

import com.alibaba.fastjson2.JSONObject;
import com.qiyu.bigdata.reportexcel.jobs.ReportJob;
import org.apache.commons.cli.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import java.util.HashMap;
import java.util.Map;

@SpringBootApplication
public class ReportExcelApplicationOnce implements CommandLineRunner {



    public static void main(String[] args) {
        SpringApplication.run(ReportExcelApplicationOnce.class, args);

    }

    @Autowired
    ReportJob reportJob;

    @Override
    public void run(String[] args) throws Exception {
        Options options=new Options();
        options.addOption("i",true,"book_id");
        options.addOption("p",true,"input parameters");

        CommandLineParser parser = new DefaultParser();
        CommandLine cli = parser.parse(options, args);
        String bookId = cli.getOptionValue("i");
        String parameters = cli.getOptionValue("p");
        if(bookId == null){
            System.out.println("未指定工作簿id");
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp("java -jar report-excel", options);
            System.exit(-1);
        }
        String[] bookIds = bookId.split(",");
        int iBookId = -1;
        Map<String, Object> dataMap = new HashMap<>();
        for (String id : bookIds) {

            try {
                iBookId = Integer.parseInt(id);
            }catch(NumberFormatException e) {
                System.err.printf("指定工作簿错误{id=%s}\n",id);
                System.exit(-1);
            }
            try {
                JSONObject json = JSONObject.parseObject(parameters);
                for (String s : json.keySet()) {
                    dataMap.put(s, json.get(s));
                }
            }catch (Exception e){
                System.err.printf("指定参数错误{parameters=%s}\n", parameters);
                System.exit(-1);
            }
            try {
                reportJob.doJob(iBookId, dataMap);
            }catch(Exception e){
                e.printStackTrace();
                System.err.println("报表任务失败。。。");
                System.exit(-1);
            }

        }


    }
}
